<template>
  <div class="goods-image">
    <div
      class="large"
      v-show="!isOutside"
      :style="[
        {
          backgroundImage: `url(${pics[currPicIndex]})`,
          backgroundPosition: `${bg.x}px ${bg.y}px`,
        },
      ]"
    ></div>
    <div class="middle" ref="imgBox">
      <img :src="pics[currPicIndex]" alt="" />
      <!-- 放大镜遮罩 -->
      <div
        class="layer"
        v-show="!isOutside"
        :style="{ left: `${left}px`, top: `${top}px` }"
      ></div>
    </div>
    <ul class="small">
      <li @mouseenter="currPicIndex = i" v-for="(img, i) in pics" :key="i">
        <img :src="img" alt="" />
      </li>
    </ul>
  </div>
</template>
<script>
import { ref, watch, reactive } from 'vue'
import { useMouseInElement } from '@vueuse/core'
export default {
  name: 'GoodsImage',
  props: {
    // 商品主图列表
    pics: {
      type: Array,
      default: () => []
    }
  },
  setup () {
    // 实现鼠标移入图片列表，展示对应的图片
    // 定义一个当前选中图片的索引值变量
    // 给每个图片绑定鼠标移入事件
    // 鼠标移入某个图片后，修改索引值变量为当前移入图片的索引
    const currPicIndex = ref(0)
    const imgBox = ref(0)
    // 实现图片放大镜

    const left = ref(0)
    const top = ref(0)
    // 背景图位置放大变量
    const bg = reactive({ x: 0, y: 0 })

    const { elementX, elementY, isOutside } = useMouseInElement(imgBox)

    watch([elementX, elementY, isOutside], () => {
      if (elementX.value < 100) {
        left.value = 0
      } else if (elementX.value > 300) {
        left.value = 200
      } else {
        left.value = elementX.value - 100
      }
      if (elementY.value < 100) {
        top.value = 0
      } else if (elementY.value > 300) {
        top.value = 200
      } else {
        top.value = elementY.value - 100
      }
      // 根据left和top值放大图片，比例2:1
      bg.x = -left.value * 2
      bg.y = -top.value * 2
    })
    return { currPicIndex, imgBox, left, top, bg, isOutside } // ...toRofs(bg)
  }
}
</script>
<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    z-index: 500;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0, 0, 0, 0.2);
      left: 0;
      top: 0;
      position: absolute;
    }
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>
